/*
 * $Id$
 *
 * Copyright 2008 HuangHuang. All rights reserved.
 */

package com.crm.web.page;

import org.apache.tapestry.html.BasePage;
import org.apache.tapestry.IPage;
import org.apache.tapestry.form.IPropertySelectionModel;
import org.apache.tapestry.form.LabeledPropertySelectionModel;
import org.apache.tapestry.event.PageBeginRenderListener;
import org.apache.tapestry.event.PageEvent;
import org.apache.tapestry.valid.ValidationDelegate;
import org.apache.tapestry.valid.ValidationConstraint;
import org.apache.tapestry.annotations.InjectPage;
import org.apache.tapestry.annotations.Bean;
import org.apache.tapestry.annotations.InjectState;
import org.apache.tapestry.annotations.Persist;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.crm.model.*;
import com.crm.service.ICustomerService;
import com.crm.service.IListboxService;
import com.crm.service.utils.ServiceUtils;
import com.crm.web.util.ListboxPropertySelectionModel;
import com.crm.web.util.Constants;
import com.javaforge.tapestry.spring.annotations.InjectSpring;

/**
 * @author <a href="mailto:huang0510@hotmail.com">HuangHuang</a>
 * @version $Id$
 */
public abstract class CustomerModify extends BasePage implements PageBeginRenderListener {

    private static Log log = LogFactory.getLog(CustomerModify.class);
    private boolean modify;

    @InjectSpring("customerService")
    public abstract ICustomerService getCustomerServ();

    @InjectSpring("listboxService")
    public abstract IListboxService getListboxServ();

    @InjectPage("CustomerAll")
    public abstract CustomerAll getCustomerAllPage();

    @InjectState("userSession")
    public abstract User getUserSession();

    @Bean
    public abstract ValidationDelegate getDelegate();

    public abstract LProduct getProductSelected();

    public abstract LCustLevel getLevelSelected();

    public abstract LCustSource getSourceSelected();

    public abstract String getCustomerName();

    public abstract String getCountry();

    public abstract String getProvince();

    public abstract String getCity();

    public abstract String getAddress();

    public abstract String getWebsite();

    public abstract String getComment();

    @Persist
    public abstract Customer getCustomerInfo();

    public abstract void setCustomerInfo(Customer customerInfo);

    public IPage goback() {
        return getCustomerAllPage();
    }

    public String infoSubmit() {
        try {
            Customer customer = getCustomerInfo();
            String customerName = getCustomerName();
            String website = getWebsite();
            String country = getCountry();
            String province = getProvince();
            String city = getCity();
            String address = getAddress();
            LProduct lproduct = getProductSelected();
            LCustLevel llevel = getLevelSelected();
            LCustSource lsource = getSourceSelected();
            String comments = getComment();

            if (null == customerName && null == website && null == country
                    && null == province  && null == city && null == address
                    && null == lproduct && null == llevel && null == lsource
                    && null == comments) {
                getDelegate().record("客户信息未发生改变", ValidationConstraint.CONSISTENCY);
                return getPageName();
            }


            if (customerName != null) {
                if (isSameName(customer.getId(), customerName)) {
                    return getPageName();
                } else {
                    customer.setCustomerName(customerName);
                }
            }

            if (website != null) {
                if (isSameWebsite(customer.getId(), website)) {
                    return getPageName();
                } else {
                    customer.setWebsite(website);
                }
            }

            if (null != country) {
                customer.setCountry(country);
            }
            if (null != province) {
                customer.setProvince(province);
            }
            if (null != city) {
                customer.setCity(city);
            }
            if (null != address) {
                customer.setAddress(address);
            }
            if (null != lproduct) {
                customer.setProduct(lproduct);
            }
            if (null != llevel) {
                customer.setLevel(llevel);
            }
            if (null != lsource) {
                customer.setSource(lsource);
            }
            if (null != comments) {
                customer.setComments(comments);
            }

            getCustomerServ().update(customer);
            getDelegate().record(Constants.MODIFIED, ValidationConstraint.CONSISTENCY);
            return "CustomerModify";
        }
        catch (Exception e) {
            log.warn(getUserSession().getUsername() + ": " + e);
            e.printStackTrace();
            getDelegate().record(e.getMessage(), ValidationConstraint.CONSISTENCY);
            return getPageName();
        }
    }

    public IPropertySelectionModel getSourceSelectionModel() {
        return new LabeledPropertySelectionModel(
                new ListboxPropertySelectionModel(Constants.L_CUST_SOURCE),
                Constants.DFT_SELECT_LABEL);
    }

    public IPropertySelectionModel getLevelSelectionModel() {
        return new LabeledPropertySelectionModel(
                new ListboxPropertySelectionModel(Constants.L_CUST_LEVEL),
                Constants.DFT_SELECT_LABEL);
    }

    public IPropertySelectionModel getProductSelectionModel() {
        return new LabeledPropertySelectionModel(
                new ListboxPropertySelectionModel(Constants.L_PRODUCT),
                Constants.DFT_SELECT_LABEL);
    }

    public void pageBeginRender(PageEvent event) {
        if (null == getUserSession() || null == getCustomerInfo()) {
            event.getRequestCycle().sendRedirect("app?page=SysPageError&service=page");
        }

        // control modify form show
        String currentLoginUser = getUserSession().getUserCode();
        String owner = getCustomerInfo().getUser().getUserCode();
        if (!currentLoginUser.equals(owner)) setModify(false);
        else setModify(true);
    }

    public void onRefresh() {
        getDelegate().clearErrors();
    }

    // control modify form show
    public void setModify(boolean modify) {
        this.modify = modify;
    }

    public boolean isModify() {
        return modify;
    }

    private boolean isSameName(String id, String name) {
        String sameCustomerName = getCustomerServ().getSameNameExcludeSelf(id, name);
        if (sameCustomerName != null) {
            String message = "已经存在名为【" + sameCustomerName + "】的客户！";
            getDelegate().record(message, ValidationConstraint.CONSISTENCY);
            return true;
        }
        return false;
    }

    private boolean isSameWebsite(String id, String website) {
        String sameWebsite = getCustomerServ().getSameWebsiteExcludeSelf(id, website);
        if (sameWebsite != null) {
            String message = "已经存在名为【" + sameWebsite + "】的网址！";
            getDelegate().record(message, ValidationConstraint.CONSISTENCY);
            return true;
        }
        return false;
    }
}
